﻿using System;
using System.Web;
using Microsoft.SharePoint;

namespace RSPDS.Core
{
    public static class RSPDS_Sites
    {
        public static void OpenSite(string url, Action<SPSite> del)
        {
            if (String.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
            if (null == del) throw new ArgumentNullException("del");
            using (var site = new SPSite(url))
            {
                del(site);
            }
        }

        public static void OpenSite(Guid id, Action<SPSite> del)
        {
            if (Guid.Empty == id) throw new ArgumentNullException("id");
            if (null == del) throw new ArgumentNullException("del");
            using (var site = new SPSite(id))
            {
                del(site);
            }
        }

        public static void CurrentSite(Action<SPSite> del)
        {
            if (null == del) throw new ArgumentNullException("del");
            if (null != SPContext.Current)
            {
                using (var site = new SPSite(SPContext.Current.Site.ID))
                {
                    del(site);
                }
            }
            else if (null != HttpContext.Current)
            {
                using (var site = new SPSite(HttpContext.Current.Request.Url.ToString()))
                {
                    del(site);
                }
            }
            else
            {
                throw new RSPDS_CoreException("SPContext and HttpContext is null");
            }
        }

        public static void OpenElevatedSite(string url, Action<SPSite> del)
        {
            SPSecurity.RunWithElevatedPrivileges(() => OpenSite(url, del));
        }

        public static void OpenElevatedSite(Guid id, Action<SPSite> del)
        {
            SPSecurity.RunWithElevatedPrivileges(() => OpenSite(id, del));
        }
    }
}
